#define _CRT_SECURE_NO_WARNINGS 1
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    void reorderList(ListNode* head) {
        if (head == nullptr || head->next == nullptr) return;
        ListNode* slow = head, * fast = head;
        while (fast && fast->next)
        {
            slow = slow->next;
            fast = fast->next->next;
        }
        ListNode* newhead = new ListNode;
        ListNode* prev = newhead, * pcur = slow, * next = slow->next;
        while (pcur)
        {
            pcur->next = prev;
            prev = pcur;
            pcur = next;
            if (next) next = next->next;
            else next = nullptr;
        }
        slow->next = nullptr;
        ListNode* cur1 = head, * cur2 = prev;
        pcur = newhead;
        while (cur2)
        {
            if (cur1 == cur2) pcur->next = cur2, cur2 = cur2->next;
            else
            {
                pcur->next = cur1;
                pcur = cur1;
                cur1 = cur1->next;
                pcur->next = cur2;
                pcur = cur2;
                cur2 = cur2->next;
            }
        }
    }
};